package com.jingbaoduo.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jingbaoduo.domain.AliPay;
import com.jingbaoduo.domain.Orders;
import com.jingbaoduo.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
//@Controller  //@RestController 请求参数
@RestController
@RequestMapping("/alipay")
public class PayTestController {

    @Autowired
    private OrdersMapper ordersMapper;

    //应用ID
    String APP_ID = "9021000129607074";
    //应用私钥
    String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCbPRP+CswxJbA16TR0ZVQxyiUWpKSt0z44uBs0S/2sJG29YGwoQy/bhpsw7SX0DslFxz5vFNdLdjDVvScDRbEKSK8F/k26g05k/sho++1gcMt2U7uBq+1iN3bTIxeamO4C/CQbz3UKBUzRygo+VKNeRBR4OfB1nK7NwP8cBUoU56nKS/yVyW2CwmkCJfkDZxy0r6AgYR5nUTY1XeaYAAA9e1+HnY2uIisLwpax6HseybjbvuU14LqTnkuNrtP/oys5R3l9nZ8wGffV8btkbKzDvWZkRp7WrkAY90P5M7prBRNnZ95tSllydSgvtTfael7pkM9sx2BjES1QPEyV0XWlAgMBAAECggEBAIY0UmFQUmC2tVSWDHwH0bbNjCy8H4YK1oLQXuxiOaalQ53xiu9vziLZhrbQffw1ADnr2wTLHqklP2i4gs6oZDqAxZb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OGVEiiE0GgPgz7GdV+O+nN7AuLYZSAdQAnc/PpKfok3ZqoJRc6wiqn/v";
    //支付宝公钥
    String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvmo2UAl1qP+Y917TVNM3UFrq1uWGl5Nh7R7KWthqC2+RzQt4eFbVdwkcVU6rGJy63gppZR2r0pYpFDmO67MqJCT+BR/4QeFQiNHA/ulWwA7TY/15q/vlNg7llRX9wHE0H+/zsuH2vc6nJOhmKWCW0bP7qR0euXFRo4qqW/PWwjreYSquIPS8Q6lqEixxg6BBZnM9J+dNiq0wGlc889cuNdbP4Rzk6P3NzlDZT6gHaWm9k8X550rV/VRHOtiRxZ0/DqrgsPFp3JOQzdeLhc7xqHm5NIQoBkqLmfvFE61y9l7dnGx3C/PYtEaPWr+Z806gRF5maew2GLIUCqqlru6eLwIDAQAB";
    //编码
    String CHARSET = "utf-8";
    //支付宝网关地址
    String serverUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";//正式 https://openapi.alipay.com/gateway.do https://openapi-sandbox.dl.alipaydev.com/gateway.do
    //签名算法的类型
    String sign_type = "RSA2";
    //卖家id
    String BUYER_ID = "2088722015114960";
    //参数回调
    String NOTIFYURL = "http://bwkp54.natappfree.cc/alipay/notify";
    //回调页面
    String RETURNURL = "http://localhost:8080/orders";
    //blhwun2989@sandbox.com
    @GetMapping("/pay")
    public void pay(AliPay aliPay ,HttpServletResponse httpResponse) throws ServletException, IOException, AlipayApiException {

        //构造sdk的客户端对象
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, sign_type);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest(); //创建AP对应的requset
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(NOTIFYURL);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(RETURNURL); //在公共参数中设置回调和通知地址
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", aliPay.getTraceNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", aliPay.getTotalAmount());
        //卖家ID
        bizContent.put("buyer_id", BUYER_ID);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "测试商品");

        /******可选参数******/
        //手机网站支付默认传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "QUICK_WAP_WAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        String form = "";

        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        System.out.println("调用成功");

    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        log.info("支付回调");
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String outTradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, ALIPAY_PUBLIC_KEY, "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                log.info("交易名称: " + params.get("subject"));
                log.info("交易状态: " + params.get("trade_status"));
                log.info("支付宝交易凭证号: " + params.get("trade_no"));
                log.info("商户订单号: " + params.get("out_trade_no"));
                log.info("交易金额: " + params.get("total_amount"));
                log.info("买家在支付宝唯一id: " + params.get("buyer_id"));
                log.info("买家付款时间: " + params.get("gmt_payment"));
                log.info("买家付款金额: " + params.get("buyer_pay_amount"));

                // 查询订单
                QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", outTradeNo);
                Orders orders = ordersMapper.selectOne(queryWrapper);

                if (orders != null) {
                    orders.setCheckoutTime(LocalDateTime.now());
                    orders.setStatus(2);
                    ordersMapper.updateById(orders);
                }
            }
        }
        return "success";
    }
}
